package com.myself.model.demo.netty.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
 * @author Czx
 */
public class ChatServerBootStrap {
    public static void main(String[] args) throws InterruptedException {
        //创建注册线程
        EventLoopGroup bossEventGroup = new NioEventLoopGroup(1);
        //创建工作线程
        EventLoopGroup workEventGroup = new NioEventLoopGroup(4);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //绑定服务端
        serverBootstrap.group(bossEventGroup, workEventGroup)
                //设置为NIO模式
                .channel(NioServerSocketChannel.class)
                //注册线程的最大等待数
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                //执行方法
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast("messageDecoder", new StringDecoder());
                        channel.pipeline().addLast("messageEncoder", new StringEncoder());

                        channel.pipeline().addLast(new ChatServerHandler());
                    }
                });
        //关闭连接和通道
        ChannelFuture sync = serverBootstrap.bind(9999).sync();

        sync.channel().closeFuture().sync();
        bossEventGroup.shutdownGracefully();
        workEventGroup.shutdownGracefully();
    }


}
